package com.bigfreakindeals.Activities;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.json.JSONObject;

import com.bigfreakindeals.R;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.LocalActivityManager;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.os.Bundle;

import com.bigfreakindeals.Activities.SessionEvents.AuthListener;
import com.bigfreakindeals.Activities.SessionEvents.LogoutListener;
import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;
import com.bigfreakindeals.Common.Tools;
import com.bigfreakindeals.Controller.ClosestSchoolListener;
import com.bigfreakindeals.Protocols.SoapHandlers.ClosestSchoolHandler;
import com.bigfreakindeals.Protocols.SoapHandlers.FacebookSignupHandler;
import com.bigfreakindeals.Protocols.SoapHandlers.LoginHandler;
import com.bigfreakindeals.Protocols.SoapHandlers.LoginWithFacebookHandler;
import com.bigfreakindeals.Protocols.SoapHandlers.SignupHandler;
import com.bigfreakindeals.Widgets.AlertManager;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebook.android.Facebook.DialogListener;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class LoginActivity extends BaseActivity implements OnClickListener, ClosestSchoolListener{

	RelativeLayout loginpage;
	RelativeLayout login;
	
	RelativeLayout signup;
	
	Button headerButtonLeft;
	Button headerButtonRight;
	Button btnSignIn;
	Button btnSignUp;
	View btnSignInWithFacebook;
	View btnForgotPassword;
	boolean isFacebookLogin = true; //or is sign up
	EditText email;
	EditText password;
	
	EditText firstname;
	EditText lastname;
	EditText signup_email;
	EditText signup_password;
	EditText verify_password;
	Spinner school;
	
	private String str_email;
	private String str_password;
	
	private String str_fname;
	private String str_lname;
	private String str_signup_email;
	private String str_signup_password;
	private String str_verifypassword;
	private String str_school;
	
	WebView webview;
	
	AlertDialog alertDialog;
	
	boolean isValidEmail;
	InputMethodManager inputmanager;
	public final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile("[a-zA-Z0-9+._%-+]{1,256}" +
			 "@" + "[a-zA-Z0-9][a-zA-Z0-9-]{0,64}" + "(" + "." + "[a-zA-Z0-9][a-zA-Z0-9-]{0,25}" +
			 ")+");
	
    public static final String PREFS_NAME = "MyPrefsFile";

	public String loginFrom = Constant.TAG_LOGINFROM_SETTINGS;
	
	String APP_API_ID = "134938833247844";
	Facebook facebook = new Facebook("134938833247844"); // Application ID of your app at facebook
	AsyncFacebookRunner asyncRunner;// = new AsyncFacebookRunner(facebook);
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
		
		getActivityView();
		System.out.println(getIntent().getStringExtra(Constant.TAG_LOGINFROM));
		if (getIntent().getStringExtra(Constant.TAG_LOGINFROM) !=null)
			loginFrom = (getIntent().getStringExtra(Constant.TAG_LOGINFROM));
			

        
	}
	
	@Override
	public void onDestroy(){
		this.unregisterReceiver(loginBroadcastReceiver);
		super.onDestroy();	
	}
	public void getActivityView(){
		
		setContentView(R.layout.login);
		
	   	((ProgressBar) findViewById(R.id.progress)).setVisibility(View.GONE);
		
		loginpage = (RelativeLayout)findViewById(R.id.headerlogin);
		loginpage.setBackgroundColor(ApplicationEx.getInstance().currentBG);
		
		headerButtonLeft = (Button)findViewById(R.id.header_iconleft);
		headerButtonLeft.setOnClickListener(this);
		headerButtonLeft.setSelected(true);
		headerButtonLeft.setTextColor(0xffffffff);
		
		headerButtonRight = (Button)findViewById(R.id.header_iconright);
		headerButtonRight.setOnClickListener(this);
		headerButtonRight.setSelected(false);
		headerButtonRight.setTextColor(0xffcacaca);
		
		login = (RelativeLayout)findViewById(R.id.login);
		login.setBackgroundDrawable(ApplicationEx.getInstance().getroundRect());
		signup = (RelativeLayout)findViewById(R.id.signup);
		signup.setBackgroundDrawable(ApplicationEx.getInstance().getroundRect());
		login.setVisibility(View.VISIBLE);
		signup.setVisibility(View.GONE);
		
			
        //buttons
        btnSignIn = (Button)findViewById(R.id.button_signin);
        btnSignIn.setOnClickListener(this);
	    btnSignIn.setFocusable(true); 
	    
        btnSignInWithFacebook = findViewById(R.id.button_loginwithfb);
        btnSignInWithFacebook.setOnClickListener(this);
        btnSignInWithFacebook.setBackgroundDrawable(ApplicationEx.getInstance().getroundRect());
		
        btnForgotPassword = findViewById(R.id.button_forgotpassword);
        btnForgotPassword.setOnClickListener(this);
        btnForgotPassword.setBackgroundDrawable(ApplicationEx.getInstance().getroundRect());
        
        btnSignUp = (Button)findViewById(R.id.button_signup);
        btnSignUp.setOnClickListener(this);
      
        email = (EditText)findViewById(R.id.email);
        email.setClickable(true);
   
        password = (EditText)findViewById(R.id.password);
        password.setClickable(true);
        
        //sign up edit text fields
        firstname = (EditText)findViewById(R.id.firstname);
        firstname.setClickable(true);
        
        lastname = (EditText)findViewById(R.id.lastname);
        lastname.setClickable(true);
        
        signup_email = (EditText)findViewById(R.id.email_edittext);
        signup_email.setClickable(true);
        signup_email.setFocusable(true);
        
        signup_email.setOnFocusChangeListener(new View.OnFocusChangeListener(){
	        public void onFocusChange(View v, boolean hasFocus) {
	        	if(v==signup_email){
	        		str_email = signup_email.getText().toString();
			        if(str_email.length()!=0){
		        		if(checkEmailFormat(str_email)){
				        	isValidEmail = true;
				        }else{
				        	alertDialog.setTitle("Invalid format");
					        alertDialog.setMessage("Please enter valid e-mail address");
					        alertDialog.show();
					        isValidEmail = false;
				        }
			        }
	        	}
	        	
	        	
	
		    }

        });
        signup_password = (EditText)findViewById(R.id.password_edittext);
        
        verify_password = (EditText)findViewById(R.id.vpassword_edittext);
        
        school = (Spinner)findViewById(R.id.school_edittext);
        
      
        updateButtons();
        
        alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	
             //here you can add functions
       
          } });	
       
       
        webview = (WebView)findViewById(R.id.termsofuseweb);
		WebViewClient webViewClientExt = new WebViewClientExtLogin();
		webview.setWebViewClient(webViewClientExt);
		webview.setVerticalScrollbarOverlay(true);
		webview.setFocusableInTouchMode(true);
		webview.setFocusable(true);
		webview.requestFocus(View.FOCUS_DOWN);
		WebSettings webSettings = webview.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); 
		webSettings.setDomStorageEnabled(true);
		webSettings.setSaveFormData(false);
		webSettings.setSavePassword(false);
		webSettings.setLoadsImagesAutomatically(true);
		webSettings.setBlockNetworkImage(false);
        
		
		 String terms = "<b>By clicking the buttons below you agreed to the "+
    	"<a href=\"TANDC\">BigFreakinDeals Terms of Use</a>"+
    	" and <a href=\"PRIVACY\">Privacy Policy</a></b>";
		
		terms = "<style type=\"text/css\">body{background-color:#d0d0d0; color: #000000; font-size: 12px;}</style>"+terms;
		
		webview.loadData(terms, "text/html", "utf-8");
			
    	
		
		this.registerReceiver(loginBroadcastReceiver, new IntentFilter(Constant.EVENTS_LOGINERROR));
		this.registerReceiver(loginBroadcastReceiver, new IntentFilter(Constant.EVENTS_LOGINSUCCESS));
		this.registerReceiver(loginBroadcastReceiver, new IntentFilter(Constant.EVENTS_SIGNUPSUCCESS));
		this.registerReceiver(loginBroadcastReceiver, new IntentFilter(Constant.EVENTS_SIGNUPERROR));
	    	   
	
		hideVirtualKeyboard();
		updateUniversityTheme();
	}
	
	
	//university specific settings in this case just BG
	public void updateUniversityTheme(){
		((RelativeLayout)findViewById(R.id.headerlogin)).setBackgroundColor(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().color_school_bg + (-16777216));
		
	}
	private void updateButtons() {
		if (headerButtonLeft.isSelected()){
			login.setVisibility(View.VISIBLE);
			signup.setVisibility(View.GONE);
			btnForgotPassword.setVisibility(View.VISIBLE);
			((TextView)findViewById(R.id.text_loginwithfb)).setText("Login with Facebook");
			
			isFacebookLogin = true;//sign in
			headerButtonLeft.setBackgroundResource(R.drawable.signin_btn_selected);
		}else {
			isFacebookLogin = false;//sign up
 			headerButtonLeft.setBackgroundResource(R.drawable.signin_btn_unselected);
			headerButtonLeft.setTextColor(0xffffffff);
			headerButtonRight.setTextColor(0xffcacaca);
			
		}
		
		if (headerButtonRight.isSelected()){
			login.setVisibility(View.GONE);
			
			signup.setVisibility(View.VISIBLE);
			
			btnForgotPassword.setVisibility(View.GONE);
			((TextView)findViewById(R.id.text_loginwithfb)).setText("Sign Up with Facebook");
			
			headerButtonRight.setBackgroundResource(R.drawable.signup_btn_selected);
		}else {
			headerButtonRight.setBackgroundResource(R.drawable.signup_btn_unselected);
			headerButtonRight.setTextColor(0xffffffff);
			headerButtonLeft.setTextColor(0xffcacaca);
			
		}
		
		if (ApplicationEx.getInstance().myProfile!=null && 
				ApplicationEx.getInstance().myProfile.getUsername()!=null && 
				ApplicationEx.getInstance().myProfile.getUsername().length() > 0){
	     	email.setText(ApplicationEx.getInstance().myProfile.getUsername());
	     	signup_email.setText(ApplicationEx.getInstance().myProfile.getUsername());
		}
		
		
	}
	
	public final class LoginDialogListener implements DialogListener {

		public void onComplete(Bundle values) {
		Toast.makeText(LoginActivity.this, "on completed.", Toast.LENGTH_LONG).show();
			
		try {
			//The user has logged in, so now you can query and use their Facebook info
			JSONObject json = Util.parseJson(facebook.request("me"));
			String facebookID = json.getString("id");
			String firstName = json.getString("first_name");
			String lastName = json.getString("last_name");
			//Toast.makeText(LoginActivity.this, "Thank you for Logging In, " + firstName + " " + lastName + "!"+" "+"Your Access Token is: "+facebook.getAccessToken(), Toast.LENGTH_SHORT).show();
			sendAccessToken(facebook.getAccessToken());
			
			//		SessionStore.save(facebook, Login.this);
		}
		catch( Exception error ) {
			Toast.makeText( LoginActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
		}
		catch( FacebookError error ) {
			Toast.makeText( LoginActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
		}
		}

		public void onFacebookError(FacebookError e, Object state){
			Toast.makeText(LoginActivity.this, "onFacebookError"+e.getMessage(), Toast.LENGTH_LONG).show();
			
		}

		public void onFacebookError(FacebookError error) {
			
		Toast.makeText(LoginActivity.this, "Something went wrong. Please try again.", Toast.LENGTH_LONG).show();
		}

		public void onError(DialogError error) {
			
		Toast.makeText( LoginActivity.this, "Something went wrong. Please try again.", Toast.LENGTH_LONG).show();
		}

		public void onCancel() {
		Toast.makeText( LoginActivity.this, "Something went wrong. Please try again.", Toast.LENGTH_LONG).show();
		}
	}
	
	
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);

	    Log.d("onActivityResult","onActivityResult");
	    facebook.authorizeCallback(requestCode, resultCode, data);
	}

		
	
	public void LoginwithFacebook(String token){
		final ArrayList<String> param = new ArrayList<String>();
		param.add(token);
		final Context context =this;
		
		new Thread() {
			@Override
			public void run() {
				try {
					sleep(5);
				} catch (Exception e) {
				}
				new LoginWithFacebookHandler(Tools.getURL(Constant.GET_LOGINWITHFACEBOOK, param ),context);
				
			}

		}.start();
	}
	public void SignUpwithFacebook(String token,String schoolname){

		final ArrayList<String> param = new ArrayList<String>();
		param.add(token);
		param.add(schoolname);
		
		final Context context =this;
		
		new Thread() {
			@Override
			public void run() {
				try {
					sleep(5);
				} catch (Exception e) {
				}
				new FacebookSignupHandler(Tools.getURL(Constant.GET_SIGNUPWITHFACEBOOK, param ),context);
				
			}

		}.start();
		ApplicationEx.getInstance().progressDialog = ProgressDialog.show(this, "Facebook Authorization is successful", "Signing Up.....");
		
	}
	
	
	public void sendAccessToken(final String token){
		System.out.println("sendAccessToken "+isFacebookLogin);
		if (isFacebookLogin){ //login to unimiser
			ApplicationEx.getInstance().progressDialog = ProgressDialog.show(this, "Login to Facebook Successful", "Connecting to BigFnCoupons now...");
			LoginwithFacebook(token);
		}else { //send sign up form 
			ApplicationEx.getInstance().progressDialog = ProgressDialog.show(this, "Facebook Authorization is successful", "Connecting to BigFnCoupons now...");
			//set school selection first
			System.out.println("school: "+ApplicationEx.getInstance().schoolListString);
		
			final String[] getSchoolListString  = Tools.getStringArray(ApplicationEx.getInstance().schoolListString);
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Select a School");
			builder.setSingleChoiceItems(getSchoolListString, -1, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// a choice has been made!
					System.out.println(token+" "+which+" "+"school: "+getSchoolListString[which]);
					
					String selectedVal = getSchoolListString[which];
					SignUpwithFacebook(token,selectedVal);
					dialog.dismiss();
				}
			});
			try{
				ApplicationEx.getInstance().progressDialog.dismiss();
			}catch (Exception e) {
				// TODO: handle exception
			}
			builder.show();
			
			
			
		}
	}
	

	
	
	public void alertOK(Context context, String message, String button){
	
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(message)
		       .setCancelable(false)
		       .setPositiveButton(button, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		               dialog.dismiss();
		               onBackPressed();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();
		
	}
	
	
	
	
	public class myAuthListener implements AuthListener {
        public void onAuthSucceed() {	           
        	Log.i("onAuthSucceed", "sampleauthlistener");
        }

        public void onAuthFail(String error) {
        	Log.i("onAuthFail", error);
         
        }
    }

    public class myLogoutListener implements LogoutListener {
        public void onLogoutBegin() {
           Log.i("onLogoutBegin", "Logging out...");
        }

        public void onLogoutFinish() {
            Log.i("onLogoutFinish", "You have logged out! ");
        }
    }
	   
private void facebooklogin(){
	
	   Toast.makeText(LoginActivity.this, "Authorizing", Toast.LENGTH_SHORT).show();
	   asyncRunner = new AsyncFacebookRunner(facebook);
		
		facebook.authorize(LoginActivity.this, new String[] { "" }, new LoginDialogListener());

	   	this.registerReceiver(loginBroadcastReceiver, new IntentFilter(Constant.EVENTS_FACEBOOK_LOGINERROR));
		this.registerReceiver(loginBroadcastReceiver, new IntentFilter(Constant.EVENTS_FACEBOOK_LOGINSUCCESS));
		this.registerReceiver(loginBroadcastReceiver, new IntentFilter(Constant.EVENTS_FACEBOOKSIGNUPSUCCESS));
		this.registerReceiver(loginBroadcastReceiver, new IntentFilter(Constant.EVENTS_FACEBOOKSIGNUPERROR));

}
	
	@Override
	public void onClick(View v) {
		hideVirtualKeyboard();
		
		//android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
		//imm.hideSoftInputFromWindow(email.getWindowToken(), 0);
		
		
		if (v == btnSignIn || v == btnSignInWithFacebook|| v == btnForgotPassword){
			int id = v.getId();
			
			switch (id) {
	
			case R.id.button_signin:

				str_email = email.getText().toString();
		        str_password = password.getText().toString();
		        
		        if ((str_email.length()==0) || (str_password.length()==0)){
		        	
					if (str_email.length()==0){
				        alertDialog.setTitle("Email address is blank");
				        alertDialog.setMessage("Please enter an email address. ");
				        alertDialog.show();
				        
				    }else if (str_password.length()==0){
						alertDialog.setTitle("Password is blank");
				        alertDialog.setMessage("Please enter a password. ");
				        alertDialog.show();
					}
					
		        }else{
		        	
		        hideVirtualKeyboard();	
		        ApplicationEx.getInstance().progressDialog = ProgressDialog.show(this, "Login", "Please wait...");
		        signIn(str_email, str_password);
		        }
				break;
				
			case R.id.button_loginwithfb:{
					facebooklogin();
				break;
			}
			case R.id.button_forgotpassword:
				launchBrowser(Tools.getURL(Constant.GET_FORGOTPASSWORD, null));
			
				break;
				
			default:
			}
		}else if (v == headerButtonLeft || v == headerButtonRight){
			Log.i("UPDATEBUTTON","Update It");
			if (v == headerButtonLeft){
				
				headerButtonLeft.setSelected(!headerButtonLeft.isSelected());
				headerButtonRight.setSelected(!headerButtonRight.isSelected());
				
			}else {
			
				headerButtonLeft.setSelected(!headerButtonLeft.isSelected());
				headerButtonRight.setSelected(!headerButtonRight.isSelected());
			
				
			}
			updateButtons();
			
			
		}else if(v == btnSignUp){
			Log.i("BUTTON", "Sign Up");
			int id = v.getId();
			hideVirtualKeyboard();
			switch (id) {
				case R.id.button_signup:

					str_fname = firstname.getText().toString();
			        str_lname = lastname.getText().toString();
			        str_signup_email = signup_email.getText().toString();
			        str_signup_password = signup_password.getText().toString();
			        str_verifypassword = verify_password.getText().toString();
			        str_school = school.getSelectedItem().toString();
			        
			        
			        if (/*(str_fname.length()==0) || (str_lname.length()==0) ||*/ /*firstname and last name is not mandatory*/ 
			        		(str_signup_email.length()==0) || (str_signup_password.length()==0) || 
			        		(str_verifypassword.length()==0) || (str_school.length()==0) ){
			        	
			        	alertDialog.setTitle("All fields are mandatory");
				        alertDialog.setMessage("Please fill out all fields in the signup form. ");
				        alertDialog.show();
			        		
			        }else if (str_signup_password.length()<6){
			        	alertDialog.setTitle("Password must be atleast 6 characters");
				        alertDialog.setMessage("Please re-enter password. ");
				        alertDialog.show();

			        }else{
			        	Log.i("ready to", "sign up"+isValidEmail);
			        	if(!str_signup_password.contentEquals(str_verifypassword)){
			        		Log.i("does not match", str_signup_password + ":" + str_verifypassword);
			        		alertDialog.setTitle("Passwords do not match");
					        alertDialog.setMessage("Please re-enter password. ");
					        alertDialog.show();
			        	}else if(isValidEmail){
			        	    ApplicationEx.getInstance().progressDialog = ProgressDialog.show(this, "Signing up", "Please wait...");
					        signUp(str_fname, str_lname, str_signup_email, str_signup_password, str_school);

			        	}
			        }
				break;
			default:
				
			}
			
		}
	}
@Override
public void onResume(){

	hideVirtualKeyboard();

	if (ApplicationEx.getInstance().schoolListMap !=null && ApplicationEx.getInstance().schoolListMap.size() >0 )
		refreshSchoolList();
	else {
		
		ApplicationEx.getInstance().controller.getSchoolListings(false);
	}
	if (ApplicationEx.getInstance().myProfile!=null && 
			ApplicationEx.getInstance().myProfile.getUsername()!=null && 
			ApplicationEx.getInstance().myProfile.getUsername().length() > 0){
     	email.setText(ApplicationEx.getInstance().myProfile.getUsername());
     	signup_email.setText(ApplicationEx.getInstance().myProfile.getUsername());
	}
	
	
	System.out.println("RESUMING 3..."+ApplicationEx.getInstance().myProfile.isLogin()+" "+ApplicationEx.getInstance().myProfile.getlastSelectedSchool());
	
    
	super.onResume();
	
}
	private void signIn(String email, String password) {
		// TODO Auto-generated method stub
			
		final ArrayList<String> params = new ArrayList<String>();
		params.add(email);
		params.add(password);
		final Context context =this;
		new Thread() {
			@Override
			public void run() {
				try {
					sleep(5);
				} catch (Exception e) {
				}
				new LoginHandler(Tools.getURL(Constant.GET_LOGIN, params ),context);
				
			}

		}.start();
		
	}
	
	private boolean checkEmailFormat(String email) {
		// TODO Auto-generated method stub
		return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
		
	}
	
	private void signUp(String str_fname2, String str_lname2, String str_signup_email2, String str_signup_password2, String str_school2){
		// TODO Auto-generated method stub
		
		final ArrayList<String> params = new ArrayList<String>();
		params.add(str_signup_email2);
		params.add(str_signup_password2);
		params.add(str_fname2);
		params.add(str_lname2);
		params.add(str_school2);
		System.out.println(str_signup_password2+" "+str_fname2+" "+str_lname2+" "+str_school2+" "+str_signup_email2);
		final Context context =this;
		new Thread() {
			@Override
			public void run() {
				try {
					sleep(5);
				} catch (Exception e) {
				}
				new SignupHandler(Tools.getURL(Constant.GET_SIGNUP, params ),context);
				
			}

		}.start();
	}

	public void hideVirtualKeyboard() {
		try {
			
			if (inputmanager==null)
				inputmanager = (InputMethodManager) LoginActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
			inputmanager.hideSoftInputFromInputMethod(LoginActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
	
		} catch (Exception e) {
			
		}
	}
	public void displayErrorMessage(String errorMessage){
		
		AlertManager.alertOK(this,errorMessage, "OK");
		
	}
	public void displayLoginSuccess(){
	 
	ApplicationEx.getInstance().progressDialog = ProgressDialog.show(this, "Login successful", "please wait...");
	
	
	if (loginFrom.compareTo(Constant.TAG_LOGINFROM_MYCOUPONS)  == 0) {
		ApplicationEx.getInstance().progressDialog.dismiss();
		new Thread() {
			@Override
			public void run(){
				try {
					sleep(10);
				} catch (Exception e) {
				}
			} 
		}.start();
		
		final ArrayList<String> params = new ArrayList<String>();
		params.add(ApplicationEx.getInstance().myProfile.university_preference_Lat);
		params.add(ApplicationEx.getInstance().myProfile.university_preference_Long);
		ApplicationEx.getInstance().currentTab = 1;
		ApplicationEx.getInstance().controller.current =  this;
		
		ApplicationEx.getInstance().currentTabState =ApplicationEx.getInstance().STATE_MYCOUPONS;
		
		new ClosestSchoolHandler(Tools.getURL(Constant.GET_CLOSESTSCHOOL, params),this,true);
		
	
		
	}else if ((loginFrom.compareTo(Constant.TAG_LOGINFROM_BUYPAGE)  == 0)){
	
		ApplicationEx.getInstance().progressDialog.dismiss();
		final ArrayList<String> params = new ArrayList<String>();
		params.add(ApplicationEx.getInstance().myProfile.university_preference_Lat);
		params.add(ApplicationEx.getInstance().myProfile.university_preference_Long);
		ApplicationEx.getInstance().currentTab = 0;
		
		ApplicationEx.getInstance().currentTabState = ApplicationEx.getInstance().STATE_BUY;
		
		Log.i("CURRENT",ApplicationEx.getInstance().currentTabState+" ");
		
		ApplicationEx.getInstance().controller.current =  this;
		
		new ClosestSchoolHandler(Tools.getURL(Constant.GET_CLOSESTSCHOOL, params),this,true);
		
		
	}else if ((loginFrom.compareTo(Constant.TAG_LOGINFROM_DISCUSS)  == 0)){
		
		//go to my coupons activity
		ApplicationEx.getInstance().progressDialog.dismiss();
	
		new Thread() {
			@Override
			public void run(){
				try {
					sleep(10);
					onBackPressed();
				} catch (Exception e) {
				}
			} 
		}.start();
		
		final ArrayList<String> params = new ArrayList<String>();
		params.add(ApplicationEx.getInstance().myProfile.university_preference_Lat);
		params.add(ApplicationEx.getInstance().myProfile.university_preference_Long);
		ApplicationEx.getInstance().currentTab = 0;
		ApplicationEx.getInstance().controller.current =  this;
		
		ApplicationEx.getInstance().currentTabState =ApplicationEx.getInstance().STATE_ACTIVEDEALS;
		
		new ClosestSchoolHandler(Tools.getURL(Constant.GET_CLOSESTSCHOOL, params),this,false);
		
	
		
	}else{
			new Thread() {
				@Override
				public void run(){
					try {
						sleep(10);
					} catch (Exception e) {
					}
				} 
			}.start();
	
		final ArrayList<String> params = new ArrayList<String>();
		params.add(ApplicationEx.getInstance().myProfile.university_preference_Lat);
		params.add(ApplicationEx.getInstance().myProfile.university_preference_Long);
		ApplicationEx.getInstance().currentTab = 0;
		
		ApplicationEx.getInstance().currentTabState =ApplicationEx.getInstance().STATE_ACTIVEDEALS;
		new ClosestSchoolHandler(Tools.getURL(Constant.GET_CLOSESTSCHOOL, params),this,true);
		
	}
	}
	
	 @Override  
	   public boolean onKeyDown(int keyCode, KeyEvent event) {
		  if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	   			if (loginFrom.compareTo(Constant.TAG_LOGINFROM_DISCUSS)  == 0) {
	   				ApplicationEx.toPost = false;
	   			}
	   			
	   			
	   		}
	       return super.onKeyDown(keyCode, event);
	   }
	 
	private void refreshSchoolList(){
	

		if (ApplicationEx.getInstance().schoolListMap!=null){
			
			ArrayAdapter<String> adapter;
			
			
			String[] getSchoolListString  = Tools.getStringArray(ApplicationEx.getInstance().schoolListString);
			adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, getSchoolListString);
	        
	        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        
	        school.setAdapter(adapter);
	        school.setSelected(true);
	        
		}
	}
	public BroadcastReceiver loginBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			ApplicationEx.getInstance().progressDialog.dismiss();
			if (intent.getAction().equals(Constant.EVENTS_FACEBOOK_LOGINERROR)) {
			   	// DO the following:
			   	//Display error message as alert
			   	// retunr back to login screen
			   	
				String errormessage = intent.getStringExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE);
			   	displayErrorMessage(errormessage);
			   	
			}else if (intent.getAction().equals(Constant.EVENTS_FACEBOOK_LOGINSUCCESS)) {
			   
				// DO the following:
			   	// get users university info( must be do in the loginhandler)
			   	// exit login page and go to the active deals screen(MainTabActivity State= activedeals);
			   	Log.i("*****username: ", ApplicationEx.getInstance().myProfile.getUsername());
			   	displayLoginSuccess();
	
			}else if (intent.getAction().equals(Constant.EVENTS_GETSCHOOLLIST)) {
				// update UI
				refreshSchoolList();

			}else if (intent.getAction().equals(Constant.EVENTS_LOGINERROR)) {
			   	// DO the following:
			   	//Display error message as alert
			   	// retunr back to login screen
			   	
				String errormessage = intent.getStringExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE);
			   	displayErrorMessage(errormessage);
			   	
			}else if (intent.getAction().equals(Constant.EVENTS_LOGINSUCCESS)) {
			   
				// DO the following:
			   	// get users university info( must be do in the loginhandler)
			   	// exit login page and go to the active deals screen(MainTabActivity State= activedeals);
			   	Log.i("*****username: ", ApplicationEx.getInstance().myProfile.getUsername());
			   	
			   	savePreferences(str_password);
			   	
				displayLoginSuccess();
			   	
			}else if (intent.getAction().equals(Constant.EVENTS_SIGNUPSUCCESS)|| intent.getAction().equals(Constant.EVENTS_FACEBOOKSIGNUPSUCCESS)){
				
				Log.i("SIGNUP ACTIVITY", "success");
				//displayErrorMessage("Signup success. Email will be sent to activate your account.");
				alertDialog.setTitle("Signup success");
		        alertDialog.setMessage("Email will be sent to activate your account. ");
		        alertDialog.show();
		    	savePreferences(str_password);
				displayLoginSuccess();
			
			}else if (intent.getAction().equals(Constant.EVENTS_SIGNUPERROR) || intent.getAction().equals(Constant.EVENTS_FACEBOOKSIGNUPERROR)){
				
				String errormessage = intent.getStringExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE);
			   displayErrorMessage(errormessage);
				Log.i("SIGNUP ACTIVITY", "ERROR");
			}
			}
	};
	private void  savePreferences(String password){
	 	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
	    SharedPreferences.Editor editor = settings.edit();
	      editor.putString("username", ApplicationEx.getInstance().myProfile.getUsername());
	      if (password !=null)
	    	  ApplicationEx.getInstance().myProfile.setPassword(password);
	      editor.putString("password", ApplicationEx.getInstance().myProfile.getPassword());
	      editor.putString("email", ApplicationEx.getInstance().myProfile.getEmail());
	      editor.putBoolean("rememberme", ApplicationEx.getInstance().myProfile.isSettings_rememberMe());
	      editor.putBoolean("newdeals", ApplicationEx.getInstance().myProfile.isSettins_notificationNewDeals());
	      editor.putBoolean("beansays", ApplicationEx.getInstance().myProfile.isSettins_notificationbeanSays());

	      Log.v("newdeals? : ", Boolean.toString(ApplicationEx.getInstance().myProfile.isSettins_notificationNewDeals()));

	      editor.commit();
	}
	
	@Override
	public void handlerResponse(boolean isSuccess,boolean isRefresh) {
		// TODO Auto-generated method stub
		ApplicationEx.getInstance().controller.getTodaysDeal(isRefresh);
		
	}
	public void getTandC(){
		//get the number
		Intent intent = new Intent(this, BrowserActivity.class);
		intent.putExtra(Constant.TAG_BROWSERTYPE, Constant.type_TandC);
		startActivity(intent);
	}

	public void getPrivacy(){
		//get the number
		Intent intent = new Intent(this, BrowserActivity.class);
		intent.putExtra(Constant.TAG_BROWSERTYPE, Constant.type_PRIVACY);
		startActivity(intent);
	}
	
	public class WebViewClientExtLogin extends WebViewClient {
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
		}
		
	    @Override
	    public boolean shouldOverrideUrlLoading(WebView view, String url) {
	    	if (url.contains("TANDC")){
	    		getTandC();
	    	}else if  (url.contains("PRIVACY")){
	    		getPrivacy();
			}
	    	return true;
	    }
	    @Override
	    public void onPageFinished(WebView view, String url) {
	    	
	    }

	}


}
